package com.ganeshkrishnan.globald.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ganeshkrishnan.globald.dao.CountryManagerDao;
import com.ganeshkrishnan.globald.dao.PersonDao;
import com.ganeshkrishnan.globald.model.CivResource;
import com.ganeshkrishnan.globald.model.MilResource;
import com.ganeshkrishnan.globald.model.Person;
import com.ganeshkrishnan.globald.web.utils.Constants;
import com.google.code.facebookapi.FacebookJsonRestClient;
import com.google.code.facebookapi.ProfileField;

@Controller
@RequestMapping("/country")
public class CountryController {
	protected final Log			logger	= LogFactory.getLog(getClass());
	@Autowired
	private CountryManagerDao	countryManagerdao;
	@Autowired
	private PersonDao			personDao;

	public PersonDao getPersonDao() {
		return personDao;
	}

	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}

	public CountryManagerDao getCountryManager() {
		return countryManagerdao;
	}

	public void setCountryManager(CountryManagerDao countryManagerdao) {
		this.countryManagerdao = countryManagerdao;
	}

	public CountryController() {
	}

	@RequestMapping(method = RequestMethod.GET)
	protected String getCountries(Model model, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String apiKey = "0bef528b7c0fb390bc2d75112be60b92";
		String secretKey = "43f82864988c4f6196fa04be5b690133";
		HttpSession session = request.getSession();
		String sessionKey = (String) session.getAttribute("restSearchAppSession");
		String authToken = request.getParameter("auth_token");
		FacebookJsonRestClient client = null;
		if (sessionKey != null) {
			client = new FacebookJsonRestClient(apiKey, secretKey, sessionKey);
		} else if (authToken != null) {
			client = new FacebookJsonRestClient(apiKey, secretKey);
			try {
				sessionKey = client.auth_getSession(authToken);
				session.setAttribute("restSearchAppSession", sessionKey);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			response.sendRedirect("http://www.facebook.com/login.php?api_key=" + apiKey);
			return null;
		}
		Long personID = Constants.PERSONID;
		try {
			personID = client.users_getLoggedInUser();
			session.setAttribute("personID", personID);
			Person p = personDao.get(personID);
			if (null == p) {
				Person person = new Person();
				person.setId(personID);
				Set<ProfileField> c = new HashSet<ProfileField>();
				c.add(ProfileField.FIRST_NAME);
				c.add(ProfileField.LAST_NAME);
				c.add(ProfileField.NAME);
				List<Long> friends = new ArrayList<Long>();
				friends.add(personID);
				JSONArray finresponse = (JSONArray) client.users_getInfo(friends, c);
				JSONObject obj = (JSONObject) finresponse.get(0);
				person.setFirstName(obj.getString("first_name"));
				person.setLastName(obj.getString("last_name"));

				Set<CivResource> resourcesSet = new HashSet<CivResource>();
				CivResource resFood = new CivResource();
				resFood.setResType(resFood.FOOD);
				resFood.setCivDeployed(6);
				resFood.setResAvailable(6000);
				resFood.setResourceUpdated(new Date());
				resourcesSet.add(resFood);
				CivResource resWater = new CivResource();
				resWater.setResType(resWater.WATER);
				resWater.setCivDeployed(5);
				resWater.setResAvailable(5000);
				resourcesSet.add(resWater);
				CivResource resHay = new CivResource();
				resHay.setResType(resHay.HAY);
				resHay.setCivDeployed(4);
				resHay.setResAvailable(4000);
				resourcesSet.add(resHay);
				CivResource resWood = new CivResource();
				resWood.setResType(resWood.WOOD);
				resWood.setCivDeployed(3);
				resWood.setResAvailable(3000);
				resourcesSet.add(resWood);
				CivResource resSilver = new CivResource();
				resSilver.setResType(resSilver.SILVER);
				resSilver.setCivDeployed(2);
				resSilver.setResAvailable(2000);
				resourcesSet.add(resSilver);

				CivResource resGold = new CivResource();
				resGold.setResType(resGold.GOLD);
				resGold.setCivDeployed(1);
				resGold.setResAvailable(1000);
				resourcesSet.add(resGold);

				CivResource resDollar = new CivResource();
				resDollar.setResType(resDollar.DOLLAR);
				resDollar.setCivDeployed(0);
				resDollar.setResAvailable(1000);
				resourcesSet.add(resDollar);

				CivResource resKarma = new CivResource();
				resKarma.setResType(resKarma.KARMA);
				resKarma.setCivDeployed(0);
				resKarma.setResAvailable(2500);
				resourcesSet.add(resKarma);

				CivResource resXP = new CivResource();
				resXP.setResType(resXP.XP);
				resXP.setCivDeployed(0);
				resXP.setResAvailable(2000);
				resourcesSet.add(resXP);

				person.setResource(resourcesSet);
				Set<MilResource> milresourcesSet = new HashSet<MilResource>();
				MilResource milArmy = new MilResource();
				milArmy.setUnitType(milArmy.ARMY);
				milArmy.setMilAvailable(600l);
				milArmy.setResourceUpdated(new Date());
				milresourcesSet.add(milArmy);
				MilResource milTank = new MilResource();
				milTank.setUnitType(milTank.TANK);
				milTank.setMilAvailable(500l);
				milTank.setResourceUpdated(new Date());
				milresourcesSet.add(milTank);
				MilResource milNavy = new MilResource();
				milNavy.setUnitType(milNavy.NAVY);
				milNavy.setMilAvailable(300l);
				milNavy.setResourceUpdated(new Date());
				milresourcesSet.add(milNavy);
				MilResource milSpies = new MilResource();
				milSpies.setUnitType(milSpies.SPIES);
				milSpies.setMilAvailable(200l);
				milSpies.setResourceUpdated(new Date());
				milresourcesSet.add(milSpies);
				MilResource milSubs = new MilResource();
				milSubs.setUnitType(milSubs.SUB);
				milSubs.setMilAvailable(100l);
				milSubs.setResourceUpdated(new Date());
				milresourcesSet.add(milSubs);
				MilResource milAir = new MilResource();
				milAir.setUnitType(milAir.AIR);
				milAir.setMilAvailable(400l);
				milAir.setResourceUpdated(new Date());
				milresourcesSet.add(milAir);
				person.setMilresource(milresourcesSet);
				personDao.save(person);
			} else {
				// Check for other conditions and redirect accordingly!
				String force = request.getParameter("f");
				if (null == force) {
					if (null != p.getCountryCode()) {
						return "redirect:/resource.html";
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		model.addAttribute("countryDetailList", this.countryManagerdao.getAll());
		return "country";
	}

	@RequestMapping(method = RequestMethod.POST)
	protected String storeCountries(@RequestParam String cCode, Model model) throws Exception {
		model.addAttribute("cd", cCode);
		return "location";
	}
}